<template>
  <div>
    <div style="overflow: hidden;">
      <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-input
            ref="input_ref"
            v-model="inputVal"
            @keyup.native="inputChange"
          />
          <!-- <el-form :inline="true"> -->
          <!-- <el-form-item>
              <el-input v-model="inputVal" placeholder="城市名称" @keyup.native="inputChange"
                        style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">获取地理位置</el-button>
            </el-form-item> -->
          <!-- <el-form-item>
              <el-input v-model="latlngCurrent" placeholder="坐标值" style="width: 246px;"></el-input>
            </el-form-item> -->
          <!-- </el-form> -->
        </el-col>
      </section>
    </div>
    <div class="mapWrap">
      <div id="qqmapCont" class="qqmap" />
      <div class="lngTips" />
    </div>

  </div>

</template>

<script>
import { getLocation } from "@/api/qxgl-yhzzgl.js";
export default {
  props: {
    mapcenter: {
      type: String,
      default: "34.759666,113.648071"
    },
    oldmarker: {
      type: String,
      default: "34.759666,113.648071"
    },
    inputDefault: {
      type: String,
      default: ""
    },
    mapKey: {
      type: String,
      required: true
    },
    lat: {
      type: String
    },
    lng: {
      type: String
    }
  },
  data: function() {
    return {
      searchName: "",
      options: [],
      searchService: null,
      qqmap: "",
      premarker: "",
      marker: "",
      inputVal: "",
      latlngCurrent: "",
      ap: null
    };
  },
  computed: {
    latLng() {
      const { lat, lng } = this;
      console.log(lat,lng)
      if (lat && lng) {
        this.qqmap.setCenter(new qq.maps.LatLng(lat, lng));
        this.premarker = new qq.maps.Marker({
          position: new qq.maps.LatLng(lat, lng),
          map: that.qqmap
        });
      }
      return {
        lat,
        lng
      };
    }
  },
  watch: {
    oldmarker(newVal, oldVal) {
      if (newVal) {
        console.log(typeof newVal);
        this.latlngCurrent = newVal;
        this.qqmap && this.createMarker();
      }
    },
    inputDefault(newVal, oldVal) {
      console.log("默认地址变成：", newVal);
      this.inputVal = newVal;
    }
  },
  mounted() {
    const that = this;
    this.inputVal = this.inputDefault;
    if (this.oldmarker) {
      this.latlngCurrent = this.oldmarker || this.mapcenter;
    }
    if (typeof (qq) === "object") {
      that.createMap();
    } else {
      this.loadQQmap();
    }
    window.onMapFileLoad = () => {
      console.log("qqmap加载完成");
      that.createMap();
      this.ap = new qq.maps.place.Autocomplete(this.$refs.input_ref.$el.querySelector("input"), {
        zIndex: 99999
      });
      that.search();
    };
  },
  methods: {
    loadQQmap() {
      const script = document.createElement("script");
      // 设置标签的type属性
      script.type = "text/javascript";
      // 设置标签的链接地址
      script.src = `https://map.qq.com/api/js?v=2.exp&key=${this.mapKey}&callback=onMapFileLoad&libraries=place`;
      // 添加标签到dom
      document.body.appendChild(script);
    },
    remoteMethod(val) {
      // 远程搜索
      if (val === "") {
        return;
      }
      this.searchService.search(val);
    },
    search(keyword) {
      const _this = this;
      // 调用Poi检索类。用于进行本地检索、周边检索等服务。
      var searchService = new qq.maps.SearchService({
        complete: function(results) {
          if (results.type === "CITY_LIST") {
            searchService.setLocation(results.detail.cities[0].cityName);
            searchService.search(keyword);
            return;
          }
          var pois = results.detail.pois;
          _this.options = pois;
          var latlngBounds = new qq.maps.LatLngBounds();
          for (var i = 0, l = pois.length; i < l; i++) {
            var poi = pois[i];
            latlngBounds.extend(poi.latLng);
            var marker = new qq.maps.Marker({
              map: _this.qqmap,
              position: poi.latLng
            });

            marker.setTitle(poi.name);
          }
          _this.qqmap.fitBounds(latlngBounds);
        }
      });
        // 添加监听事件
      qq.maps.event.addListener(this.ap, "confirm", function(res) {
        keyword = res.value;
        searchService.search(keyword);
      });
    },
    inputChange() {
      console.log(",",this.inputVal);
      this.search(this.inputVal)
      this.$emit("addr", this.inputVal); // 地图点击坐标 传递给父组件
    },
    createMap() {
      const that = this;
      this.qqmap = new qq.maps.Map(document.getElementById("qqmapCont"), {
        center: new qq.maps.LatLng(that.mapcenter.split(",")[0], that.mapcenter.split(",")[1]), // 地图的中心地理坐标。
        zoom: 12 // 地图的中心地理坐标。
      });
      setTimeout(() => {
        this.createMarker();
        this.bindMapEvent();
      }, 500);
    },
    createMarker() {
      const that = this;
      if (that.premarker) {
        that.premarker.setMap(null);
      }
      if (this.lat && this.lng) {
        const { lat, lng } = this;
        this.qqmap.setCenter(new qq.maps.LatLng(lat, lng));
        this.premarker = new qq.maps.Marker({
          position: new qq.maps.LatLng(lat, lng),
          map: that.qqmap
        });
        return;
      }
      if (this.oldmarker) {
        console.log("编辑模式：", this.oldmarker);
        that.qqmap.setCenter(new qq.maps.LatLng(that.oldmarker.split(",")[0], that.oldmarker.split(",")[1]));
        that.premarker = new qq.maps.Marker({
          position: new qq.maps.LatLng(that.oldmarker.split(",")[0], that.oldmarker.split(",")[1]),
          map: that.qqmap
        });
      } else {
        // 获取城市列表接口设置中心点
        const citylocation = new qq.maps.CityService({
          complete: function(result) {
            that.qqmap.setCenter(result.detail.latLng);
          }
        });
          // 调用searchLocalCity();方法
        citylocation.searchLocalCity();
      }
    },
    bindMapEvent() {
        console.log("7777")
      const that = this;
      // 地图点击事件
      qq.maps.event.addListener(that.qqmap, "click", function(event) {
        console.log(event);
        that.marker && that.marker.setMap(null);
        that.premarker && that.premarker.setMap(null);
        that.$emit("mapclick", event.latLng); // 地图点击坐标 传递给父组件
        that.latlngCurrent = event.latLng.lat + "," + event.latLng.lng;
        const { lat, lng } = event.latLng;
        getLocation({
          location: `${lat},${lng}`,
          key: that.globalMapKey
        }).then((res) => {
          console.log(res);
          const { message, result } = res.data;
          if (message === "query ok") {
            //    成功
            const { address_component, address, formatted_addresses } = result;
            this.inputVal = `${address}${formatted_addresses.recommend}`;
            const { nation, province, city, district, street, street_number } = address_component || {};
            // 省市县
            that.$emit("update:lng", lng);
            that.$emit("update:lat", lat);
            that.$emit("changedw", {
              lat,
              lng,
              nation,
              province,
              city,
              district,
              street,
              street_number,
              formatted_addresses
            });
          }
        }).catch((e) => {
          console.log(e);
        });
        that.marker = new qq.maps.Marker({
          position: event.latLng,
          map: that.qqmap
        });
      });
      // 地图鼠标滑动事件
      const $lngTipsBox = document.querySelector(".lngTips");
      const mapBoxWidth = window.getComputedStyle(document.querySelector(".mapWrap")).width;
      qq.maps.event.addListener(that.qqmap, "mousemove", function(event) {
        $lngTipsBox.style.display = "block";
        $lngTipsBox.style.top = (event.pixel.y + 10) + "px";
        $lngTipsBox.style.left = (event.pixel.x + 15) + "px";
        $lngTipsBox.innerText = "点击选择此坐标：" + event.latLng.lat + "," + event.latLng.lng;
      });
      // 鼠标离开
      qq.maps.event.addListener(that.qqmap, "mouseout", function(event) {
        $lngTipsBox.style.display = "none";
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .qqmap { width:100%; height:400px; }
  .mapWrap { position:relative; width:100%; height:400px; overflow:hidden; margin-top:15px; }
  .lngTips { display:none; width:255px; height:40px; padding:5px 7px; overflow:hidden; position:absolute; left:0; top:0; z-index:123456; background:#ffffff; border-radius:5px;
    line-height:20px; box-shadow:#eeeeee 1px 1px 3px; border:#eeeeee 1px solid; font-size:12px; }
</style>
